/**
 * 
 */
package fr.fermeManager.library.utils;

import java.io.IOException;
import java.io.Reader;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.commons.io.IOUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * @author Mo
 * 
 */
public class MybatisUtil {

//	private static final Logger logger = Logger.getLogger(MybatisUtil.class);
	private static final String resource = "mybatis-config.xml";
	
	private static SqlSessionFactory sqlSessionFactory;

	static {

		String driver = "org.apache.derby.jdbc.EmbeddedDriver";
		
		
		try {
			Class.forName(driver).newInstance();
		 } catch (Exception ex) {
	            ex.printStackTrace();
	       } 
		
		
		Reader reader = null;
		try {
			reader = Resources.getResourceAsReader(resource);
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
			
		} catch (IOException e) {
			e.printStackTrace();
//			logger.error(e);
		} finally {
			IOUtils.closeQuietly(reader);
		}
	}

	public static SqlSession getSession() {
		return sqlSessionFactory.openSession();
	}
	
	public static void fermerBdd() throws Exception{
		try {
			DriverManager.getConnection("jdbc:derby:;shutdown=true");
		} catch (SQLException e) {
			if (((e.getErrorCode() == 50000)
			        && ("XJ015".equals(e.getSQLState())))) {
			}else{
				throw e;
			}
		}
	}
}
